from django.shortcuts import render, HttpResponse, redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse
from web import models
from utils.tencent.cos import create_bucket
import time
from xpinyin import Pinyin


def project_list(request):
    """项目列表"""
    project_dic={'star':[],'my':[],'join':[]}
    if request.method == 'GET':
        my_project_list=models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dic['star'].append({"value":row,"type":"my"})
            else:
                project_dic['my'].append(row)

        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dic['star'].append({"value":item.project,"type":"join"})
            else:
                project_dic['join'].append(item.project)

        form = ProjectModelForm(request)
        return render(request, 'project_list.html', locals())

    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        p=Pinyin()
        name=form.cleaned_data['name']
        name=p.get_pinyin(name)
        #为项目创建一个桶
        bucket='{}-{}-{}-1311491624'.format(name,request.tracer.user.mobile_phone,str(int(time.time())))
        region='ap-chengdu'
        create_bucket(bucket,region)

        #把桶和区域写入到数据库

        # 验证通过：项目名，颜色，描述+creator谁创建的项目？
        form.instance.bucket=bucket
        form.instance.region = region
        form.instance.creator = request.tracer.user
        # 创建项目
        instance=form.save()

        issues_type_object_list=[]
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_object_list.append(models.IssuesType(project=instance,title=item))
        models.IssuesType.objects.bulk_create(issues_type_object_list)

        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request,project_type,project_id):
    if project_type=='my':
        models.Project.objects.filter(id=project_id,creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    if project_type=='join':
        models.ProjectUser.objects.filter(project_id=project_id,user=request.tracer.user).update(star=True)
        return redirect('project_list')

    return HttpResponse('请求错误')

def project_unstar(request,project_type,project_id):
    if project_type=='my':
        models.Project.objects.filter(id=project_id,creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type=='join':
        models.ProjectUser.objects.filter(project_id=project_id,user=request.tracer.user).update(star=False)
        return redirect('project_list')

    return HttpResponse('请求错误')

